package com.cztv.vote.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cztv.vote.bean.ReturnValBean;
import com.cztv.vote.service.VoteManager;

public class VotedCheckServlet extends HttpServlet {

	private static final long serialVersionUID = -6868404791033360898L;

	private VoteManager voteManager;

	@Required
	public void setVoteManager(VoteManager voteManager) {
		this.voteManager = voteManager;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext servletContext = config.getServletContext();
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext
				.getAutowireCapableBeanFactory();
		autowireCapableBeanFactory.configureBean(this, "voteManager");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String voteId = request.getParameter("voteId");
		String jsoncallback = request.getParameter("jsoncallback");
		String ip = request.getRemoteAddr();
		String info = "";
		int rid = 0;
		boolean flag = true;

		if (voteId == "" || voteId == null) {
			flag = false;
			info = "投票id无效";
		} else {
			rid = Integer.parseInt(voteId);
			ReturnValBean val = voteManager.isEnableVote(ip, rid);
			if (!val.isBoolVal()) {
				flag = false;
				info = val.getInfo();
			} else {
				val = voteManager.voteCheck(rid);
				if (!val.isBoolVal()) {
					flag = false;
					info = val.getInfo();
				}
			}
		}

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		StringBuilder outputStr = new StringBuilder();
		outputStr.append(jsoncallback);
		outputStr.append("({\"info\":\"");
		outputStr.append(info);
		outputStr.append("\",\"flag\":\"");
		outputStr.append(flag);
		outputStr.append("\"})");
		out.print(outputStr.toString());

		out.flush();
		out.close();
	}

}
